package com.example.demo.core.util;

import com.google.common.io.ByteStreams;
import com.google.common.io.Closer;
import com.google.common.io.Files;
import com.xiaoleilu.hutool.http.HttpUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpClientUtil {

    private static Log log = LogFactory.getLog(HttpClientUtil.class);

    private static HttpClientUtil httpClientUtil = null;
    private RequestConfig requestConfig = RequestConfig.custom()
            .setSocketTimeout(15000)
            .setConnectTimeout(15000)
            .setConnectionRequestTimeout(15000)
            .build();

    private HttpClientUtil() {
    }


    public static HttpClientUtil me() {
        if (httpClientUtil == null) {
            httpClientUtil = new HttpClientUtil();
        }
        return httpClientUtil;
    }




    public String httpPost(String url,Map<String, String> heads,Map<String, String> parms) {

        HttpPost post = new HttpPost(url);


        setHeand(post,heads);

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        for (String key : parms.keySet()) {
            nameValuePairs.add(new BasicNameValuePair(key, parms.get(key)));
        }
        try {
            post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }


            return httpPost(post);

    }

    public String httpPost(String url) {


        HttpPost post = new HttpPost(url);


        return httpPost(post);

    }

    public String httpPost(HttpPost post) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;

        try {
            httpClient = HttpClients.createDefault();

            post.setConfig(requestConfig);

            response = httpClient.execute(post);

            entity = response.getEntity();

            if(200 == response.getStatusLine().getStatusCode()){
                responseContent = EntityUtils.toString(entity, "UTF-8");
            }

            if(302 == response.getStatusLine().getStatusCode()){
                Header[] headers =  response.getAllHeaders();
                for(Header header : headers){
                    log.info("head:"+header.getValue());
                }
            }


        } catch (IOException e) {

            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();

                }
            } catch (IOException e) {

                e.printStackTrace();
            }

            return responseContent;

        }
    }


    public String httpGet(String url) {
        HttpGet get = new HttpGet(url);

        return httpGet(get);
    }

    public String httpGet(String url, Map<String, String> heads) {
        HttpGet get = new HttpGet(url);

        setHeand(get,heads);

        return httpGet(get);
    }


    public String httpGet(HttpGet get) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;

        try {
            httpClient = HttpClients.createDefault();

            get.setConfig(requestConfig);

            response = httpClient.execute(get);

            entity = response.getEntity();

            if(200 == response.getStatusLine().getStatusCode()){
                responseContent = EntityUtils.toString(entity, "UTF-8");
            }

            if(403 == response.getStatusLine().getStatusCode()){

                log.error("result:"+ EntityUtils.toString(entity, "UTF-8"));
            }

            if(302 == response.getStatusLine().getStatusCode()){
                Header[] headers =  response.getAllHeaders();
                for(Header header : headers){
                    log.info("head:"+header.getValue());
                }
            }


        } catch (IOException e) {

            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();

                }
            } catch (IOException e) {

                e.printStackTrace();
            }

            return responseContent;
        }


    }

    public void setHeand(HttpRequestBase http,Map<String,String> heads  ){
        if(heads!=null){
            for (Map.Entry<String, String> entry : heads.entrySet()) {

                http.setHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    public void copyFile(String savePath,InputStream in){

        Closer closer = Closer.create();
        try {
            File imageDir = new File(savePath);
            if(!imageDir.exists()) {
                imageDir.mkdirs();
            }
            String fileName =  StringUtils.substringBefore(savePath, "?");
            fileName = StringUtils.substringAfterLast(fileName, "/");
            File imageFile = new File(imageDir, fileName);

            Files.write(ByteStreams.toByteArray(in), imageFile);

        } catch(Exception ex) {
            ex.printStackTrace();
            log.error("image download error :"+savePath);
        } finally {
            try {
                closer.close();
            } catch (IOException e) {
                closer = null;
            }
        }
    }


    public boolean uploadFile(String url,String file,Map<String,String> heads){
        boolean result = false;
        HttpPost post = new HttpPost(url);

        setHeand(post,heads);

        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity = null;

        File bin = new File(file);

        entity = MultipartEntityBuilder.create().addPart("file",new FileBody(bin)).build();

        post.setEntity(entity);


        try {
            httpClient = HttpClients.createDefault();
            post.setConfig(requestConfig);
            response = httpClient.execute(post);

            if(200 == response.getStatusLine().getStatusCode()) {
                result = true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            // 关闭连接,释放资源
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();

                }
            } catch (IOException e) {

                e.printStackTrace();
            }
        }

        return result;
    }

    public boolean uploadFile(String url,String file){
        return uploadFile(url,file,null);
    }


    public boolean downLoadFile(String savePath,String filePath,Map<String,String> heads){
        HttpGet get = new HttpGet(filePath);

        setHeand(get,heads);

        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity = null;

        try {
            httpClient = HttpClients.createDefault();

            get.setConfig(requestConfig);

            response = httpClient.execute(get);
            entity  = response.getEntity();
            if(200 == response.getStatusLine().getStatusCode()) {
                copyFile(savePath,entity.getContent());
            }
        } catch (IOException e) {

            e.printStackTrace();
        }finally {
            // 关闭连接,释放资源
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();

                }
            } catch (IOException e) {

                e.printStackTrace();
            }
        }
        return true;
    }
}